package com.qhhc.controller;

import com.qhhc.entity.CarEn;
import com.qhhc.entity.CarPhoto;
import com.qhhc.service.CarEnService;
import com.qhhc.service.CarPhotoService;
import com.qhhc.vo.CarEnVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/cars")
@CrossOrigin(origins = "http://localhost:5173")
public class CarEnController {

    @Autowired
    private CarEnService carEnService;
    @Autowired
    private CarPhotoService carPhotoService;

    @GetMapping
    public List<CarEnVo> getAllCars() {
        List<CarEn> allCars = carEnService.getAllCars();
        List<CarPhoto> allMainPhoto = carPhotoService.getAllMainPhoto();
        Map<Long, String> carIdUrlMap = allMainPhoto.stream()
                .collect(Collectors.toMap(
                        CarPhoto::getCarId,    // 键：CarPhoto 的 carId 字段
                        CarPhoto::getPhotoUrl, // 值：CarPhoto 的 photoUrl 字段
                        (oldValue, newValue) -> newValue // 处理重复键的策略（保留新值覆盖旧值）
                ));

        List<CarEnVo> carEnVoList = new ArrayList<>();
        for (CarEn carEn : allCars) {
            CarEnVo carEnVo = new CarEnVo();
            BeanUtils.copyProperties(carEn, carEnVo); // 复制同名属性
            carEnVo.setImage(carIdUrlMap.get(carEn.getCarId())); // 单独设置 image
            carEnVoList.add(carEnVo);
        }

        return carEnVoList;
    }

    @GetMapping("/list")
    public List<CarEn> list() {
        return carEnService.getAllCars();
    }

    @GetMapping("/popular")
    public List<CarEn> getPopularCars() {
        return carEnService.getPopularCars();
    }

    @GetMapping("/{id}")
    public CarEn getById(@PathVariable("id") Long id) {
        return carEnService.getCarById(id);
    }

    @PostMapping("/add")
    public boolean add(@RequestBody CarEn car) {
        return carEnService.addCar(car);
    }

    @PostMapping("/update")
    public boolean update(@RequestBody CarEn car) {
        return carEnService.updateCar(car);
    }

    @GetMapping("/delete/{id}")
    public boolean delete(@PathVariable("id") Long id) {
        return carEnService.deleteCar(id);
    }

    @GetMapping("/export")
    public void export() {
        // 导出功能实现
    }
} 